//
//  KLFPSLabel.m
//  KLBookCollection
//
//  Created by apple on 2019/1/15.
//  Copyright © 2019年 bonc. All rights reserved.
//

#import "KLFPSLabel.h"
#import "KLWeakDisplayLink.h"

@interface KLFPSLabel ()<KLWeakDisplayLinkDelegate>
@property (nonatomic, strong) KLWeakDisplayLink *link;
@property (nonatomic, assign) NSUInteger count;
@property (nonatomic, assign) NSTimeInterval lastTime;
@end

@implementation KLFPSLabel
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self setup];
    }
    return self;
}

- (void)dealloc {
    [_link stop];
}

- (void)setup {
    _link = [[KLWeakDisplayLink alloc] init];
    _link.delegate = self;
    self.text = @"fps 0";
    [_link start];
}

- (void)tick:(KLWeakDisplayLink *)displayLink {
    if (_lastTime == 0) {
        _lastTime = displayLink.timestamp;
        NSLog(@"First Tick: %f", CFAbsoluteTimeGetCurrent());
        return;
    }
    _count++;
    NSTimeInterval delta = displayLink.timestamp - _lastTime;
    if (delta>=1) {
        _lastTime = displayLink.timestamp;
        double fps = _count / delta;
        _count = 0;
        self.text = [NSString stringWithFormat:@"fps %d", (int)fps];
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
